<?php

App::uses('AppController', 'Controller');

class LocationReservationsController extends AppController {
    
    public $uses = array('LocationReservation');
    
    public $paginate = array(
        'limit' => ITEMS_PER_PAGE
    );
    
    public function index() {
        $filter = $this->parseFilterData('LocationReservation');
        $this->setFilterData($filter);
        
        $this->paginate['order'] = "{$filter->sortBy} {$filter->sortDir}";
        $this->set('reservations', $this->paginate('LocationReservation', $filter->conditions));
    }
    
    private function _setCommonData() {
        $this->set('locations', $this->LocationReservation->Location->find('list'));
        $this->set('clients', $this->LocationReservation->Client->find('list'));
    }
    
    public function create() {
        $this->_setCommonData();
        
        $data = array();
        if (! empty($this->params->query['location'])) {
            $data['location_id'] = $this->params->query['location'];
        }
        
        $this->set('data', $this->LocationReservation->create($data));
        $this->render('form');
    }
    
    public function edit($id) {
        $this->_setCommonData();
        $this->set('data', $this->LocationReservation->findById($id));
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        if (! empty($data)) {
            $this->LocationReservation->create($data);
            
            if (! $this->LocationReservation->validates()) {
                $this->setFlash('Uneti podaci nisu validni');
                $this->_setCommonData();
                $this->set('data', $data);
                return $this->render('form');
            }
            
            if (! $this->LocationReservation->save($data)) {
                $this->setFlash('Greška pri čuvanju podataka.');
                $this->_setCommonData();
                $this->set('data', $data);
                return $this->render('form');
            }
            
            $this->setFlash('Rezervacija je uspešno sačuvana.', 'ok');
            $this->redirect("edit/{$this->LocationReservation->id}");
        }
        
        $this->redirect('index');
    }
    
    public function remove($id) {
        if ($this->LocationReservation->delete($id)) {
            $this->setFlash('Rezervacija je uspešno obrisana.', 'ok');
        } else {
            $this->setFlash('Greška pri brisanju rezervacije.');
        }
        $this->redirect('index');
    }
    
}
